$(function () {
    $.fn.capitalize = function () {
        array = $(this).text().split(' ');
        capitalized = '';
        doNotCapitalize = ["a", "an", "and", "as", "at", "but", "by", "etc", "for", "in", "into", "is", "nor", "of", "off", "on", "onto", "or", "so", "the", "to", "unto", "via"];
        $.each(array, function (index, value) {
            if (index === 0 || $.inArray(value, doNotCapitalize) === -1)
                capitalized += value.charAt(0).toUpperCase() + value.slice(1);
            else
                capitalized += value;

            if (array.length != (index + 1))
                capitalized += ' ';
        });
        $(this).text(capitalized);
    };
    $.fn.wysiwygEvt = function () {
        return this.each(function () {
            var $this = $(this);
            var htmlold = $this.html();
            $this.on('keydown keyup paste copy cut mouseup', function () {
                var htmlnew = $this.html();
                if (htmlold !== htmlnew) {
                    $this.trigger('change')
                }
            })
        })
    }
    var interval = null;
    $('.menutoggle').click(function () {
        if ($(window).width() < 768) {
            $('.leftpanel').toggleClass('active')
            $('.mainpanel').toggleClass('active')
        } else {
            $('.leftpanel').removeClass('active')
            $('.mainpanel').removeClass('active')
        }
    })
    //When unchecking the checkbox
    $("#check-all").on('ifUnchecked', function (event) {
        //Uncheck all checkboxes
        $("input[type='checkbox']").iCheck("uncheck");
    });
    //When checking the checkbox
    $("#check-all").on('ifChecked', function (event) {
        //Check all checkboxes
        $("input[type='checkbox']").iCheck("check");
    });
    function generateHexString(length) {
        var ret = "";
        while (ret.length < length) {
            ret += Math.random().toString(16).substring(2);
        }
        return ret.substring(0, length);
    }

    $('.keyGenerate').on('click', function () {
        $('#' + $(this).data('id')).val(generateHexString(58));
    })
    $('select').select2();
    var ajax_call;

    var bulk_upload = {
        status_url: false,
        append: true,
        init: function () {
            $('.start_upload').on('click', function () {
                $(this).button('loading')
                bulk_upload.start_upload($(this).data('start'));
                bulk_upload.status_url = $(this).data('status');
                bulk_upload.get_status();
            })
        },
        start_upload: function (url) {
            bulk_upload.before_load_compete();
            $.post(url, $('.bulKUpload_form').serialize(), function (r) {
                bulk_upload.append = false;
                clearInterval(ajax_call)
                $('.start_upload').text('completed')
                $('.well .process .appened').html(r)
                $('.progress').removeClass('progress-striped active')
                bulk_upload.after_load_compete();
            })
        },
        get_status: function () {
            ajax_call = setInterval(function () {
                $.get(bulk_upload.status_url, function (r) {
                    if (bulk_upload.append) {
                        $('.well .process .appened').html(r)
                    }
                })
            }, 3000);
        },
        after_load_compete: function () {
            $('.well .process .spinner').addClass('hide')
        },
        before_load_compete: function () {
            $('.well .process .spinner').removeClass('hide')
        }

    }
    bulk_upload.init();
    if ($('.redactor').length) {
        $('.redactor').redactor({ minHeight: 172  });
    }
    wallpaper_page = {
        bad_words: false,
        init: function () {
            this.capitalize();
            if ($('.bad_words').length)
                this.bad_words = JSON.parse($('.bad_words').text());
            $('.content_edit').wysiwygEvt();
            this.on_change_content_edit();
            this.onClickSave();
        },
        on_change_content_edit: function () {
            $('.content_edit').on('change', function () {
                var id = $(this).data('id')
                $('#' + id).val($(this).text())
            })
        },
        onClickSave: function () {
            $('.save_wall').on('click', function () {
                var ws_id = $(this).data('id');
                $('.' + ws_id + '_load').removeClass('hide');
                $('.' + ws_id).addClass('loading').removeClass('success').find('.view_page_link').addClass('disabled');
                $(this).button('loading')
                $.post($(this).data('url'), $('.' + ws_id).find('input,select').serialize(), function (r) {
                    $('.' + ws_id + '_load').addClass('hide');
                    $('.' + ws_id).find('.save_wall').button('reset')
                    $('.' + ws_id).removeClass('loading').addClass('success');
                })
            })
        },
        capitalize: function () {
            $('.single_controls .capitalize').on('click', function () {
                var wid = $(this).data('wid');
                var wall = $('.ws_' + wid);
                var name = wall.find('.name');
                var slug = wall.find('.slug');
                var clean_words_name = wallpaper_page.remove_bad_words(name.text());
                name.text(clean_words_name).capitalize()

                var clean_words_slug = wallpaper_page.remove_bad_words((slug.text() ? slug.text() : name.text()));
                slug.text(wallpaper_page.proper_slug(clean_words_slug));
                $('.content_edit').trigger('change');
            })
        },
        proper_slug: function (slug) {
            slug = slug.replace(/[:;[}\]{+=_\/?<>,'"`~]/img, " ")
                .replace(/\s+/ig, ' ')
                .replace(/\s/ig, '-')
                .replace(/(^\-|\-$)/ig, "")
            return slug.toLowerCase();
        },
        remove_bad_words: function (text) {
            var replace_text = text.replace(/[_\s&*()^%$#@!]/ig, ' ');
            $.each(this.bad_words, function (i, e) {
                var re = new RegExp(e, "ig");
                replace_text = replace_text.replace(re, ' ');
            })
            replace_text = $.trim(replace_text.replace(/\s+/, ' '));
            return replace_text;
        }
    }
    wallpaper_page.init();
})